<?php

/*
 * Author: Quan Van Sinh
 * Email: sinhvnb@vietnambiz.com
 */

class search {

    function search() {
        
    }

    function checkKeywordExist($keyword) {
        global $db;
        $sql = "SELECT * FROM search_keyword WHERE keyword = '$keyword'";
        $rs = $db->query_first($sql);
        if ($rs['id']) {
            return true;
        } else {
            return false;
        }
    }

    function doSearch() {
        global $db, $config;
        
        $keyword = filter($config['keyword']);
        $checkExist = $this->checkKeywordExist($keyword);
        if ($config['page'] == 1 && trim($keyword)!='') {
            if ($checkExist == true) {
                $sqlUpdateKeyWordCount = "UPDATE search_keyword SET count=count+1 WHERE keyword='" . $keyword . "'";
                $db->query($sqlUpdateKeyWordCount);
            } else {
                $sqlInsertKeyword = "INSERT INTO search_keyword (keyword) values ('" . $keyword . "')";
                $db->query($sqlInsertKeyword);
            }
        }
        
        $sql = "SELECT count(id) as numrows FROM article WHERE (title LIKE '%$keyword%' OR description LIKE '%$keyword%') AND status='yes'";
        $rsTotalRows = $db->query_first($sql);
        
        $totalRows = intval($rsTotalRows['numrows']);
        $totalPages = ceil($totalRows / $config ['total_article_on_category']);
        $start = (($config ['page'] * $config ['total_article_on_category']) - $config ['total_article_on_category']);
        $limit = $config ['total_article_on_category'];

        $sql2 = "SELECT * FROM article WHERE (title LIKE '%$keyword%' OR description LIKE '%$keyword%') AND status='yes' ORDER BY create_date DESC LIMIT $start,$limit";
        $rsArticles = $db->query($sql2);
        $result = array();
        while ($row = $db->fetch_array($rsArticles)) {
            $result[$row['id']] = $row;
        }
        return array(
            "totalRows" => $totalRows,
            "totalPages" => $totalPages,
            "arrRs" => $result
        );
        
        
    }

}

?>
